<template>
  <c-view>
    <template v-slot:header>
      <div class="title">
        {{ $route.meta.title }}
        <el-button type="primary" :size="size" icon="el-icon-plus" @click="showDialog">新增计费规则</el-button>
      </div>
    </template>
    <div class="main__box">
      <c-table
        ref="cTable"
        selection
        hasBorder
        :max-height="maxHeight"
        :size="size"
        :loading="isLoading"
        :table-header="tableHeader"
        :table-list="tableList"
        :table-inner-btns="tableInnerBtns"
        :page-info="pageInfo"
        @change-pagination="changePagination"
      >
        <template v-slot:header>
          <c-search :form-model="searchObj" :form-items="searchItems" @submit-form="searchSubmit" @reset-form="searchReset"></c-search>
        </template>
      </c-table>
    </div>
    <div v-if="dialogObj.isShow">
      <c-dialog
        class="dialog-box"
        :is-show="dialogObj.isShow"
        :title="dialogObj.title"
        close-btn
        @before-close="dialogObj.isShow = false"
        @on-submit="dialogConfirm"
      >
        <rent-add ref="childRef" :init-data.sync="dialogObj.initData" :is-edit="dialogObj.isEdit"></rent-add>
      </c-dialog>
    </div>
  </c-view>
</template>

<script>
import mixinTable from 'mixins/table'
import CDialog from 'components/dialog'
import utils from 'utils'
import dictObj from '@/store/dictData'
import RentAdd from './add'

export default {
  name: 'chargingRent',
  mixins: [mixinTable],
  components: {
    CDialog,
    RentAdd
  },
  data(vm) {
    return {
      // 对话框对象
      dialogObj: {},
      // 表格内操作按钮
      tableInnerBtns: [
        {
          name: '编辑',
          icon: 'el-icon-edit',
          width: 130,
          handle(row) {
            vm.confirmTip('套餐编辑保存后客户将不可见，需再次启用套餐，确定编辑？', () => {
              const { id, name, days, money, beforeMoney, startTime, endTime, list, describe, sort, modelId } = row
              vm.showDialog({
                title: '编辑长租计费规则',
                isEdit: true,
                initData: {
                  id,
                  name,
                  days,
                  money: money / 100,
                  beforeMoney: beforeMoney / 100,
                  startTime,
                  endTime,
                  isUse: 0,
                  list,
                  sort,
                  modelId,
                  describe
                }
              })
            })
          }
        },
        {
          name: '启用',
          icon: 'el-icon-unlock',
          notBtn: row => row.isUse === 1,
          handle(row) {
            vm.disabledStatus({
              id: row.id,
              isUse: 1
            })
          }
        },
        {
          name: '禁用',
          icon: 'el-icon-lock',
          width: 100,
          notBtn: row => row.isUse === 0,
          handle(row) {
            vm.confirmTip('禁用后此计费套餐客户将不可见，确定禁用？', () => {
              vm.disabledStatus({
                id: row.id,
                isUse: 0
              })
            })
          }
        }
      ],
      tableHeader: [
        {
          label: '所属企业',
          prop: 'companyName'
        },
        {
          label: '车辆类型',
          prop: 'modelName',
          width: 100
        },
        {
          label: '套餐名称',
          prop: 'name',
          width: 120,
          search: {
            type: 'input'
          }
        },
        {
          label: '套餐天数',
          prop: 'days',
          width: 100
        },
        {
          label: '套餐优惠价(元)',
          prop: 'money',
          width: 120,
          formatter: row => row && utils.formatMoney(row.money)
        },
        {
          label: '套餐原价(元)',
          prop: 'beforeMoney',
          width: 120,
          formatter: row => row && utils.formatMoney(row.beforeMoney)
        },
        {
          label: '开始时间',
          prop: 'startTime',
          width: 160
        },
        {
          label: '结束时间',
          prop: 'endTime',
          width: 160,
          formatter: row => (row && row.endTime ? row.endTime : '长期有效')
        },
        {
          label: '是否启用',
          prop: 'isUse',
          width: 100,
          formatter: row => row && vm.setTableColumnLabel(row.isUse, 'disabledStatus'),
          search: {
            type: 'dict',
            optionsList: dictObj.disabledStatus
          }
        },
        {
          label: '排序',
          prop: 'sort',
          width: 80
        },
        {
          label: '明细',
          prop: 'list',
          width: 200,
          vHtml: row => {
            let htmlContent = ''
            row.list.forEach(res => {
              htmlContent += `<p>${res.name}：${res.detail}</p>`
            })
            return htmlContent
          }
        },
        {
          label: '创建时间',
          prop: 'creatTime',
          width: 160
        }
      ]
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    /*
     * 查询表格列表数据
     */
    fetchData() {
      const { pageNo, pageSize } = this.pageInfo
      const { dateTime, ...other } = this.searchObj
      const searchDate = this.getSearchDate(dateTime)
      this.isLoading = true
      this.$api.settings
        .fetch('rentthePackageList', {
          ...searchDate,
          ...other,
          rows: pageNo,
          offset: pageSize
        })
        .then(res => {
          this.isLoading = false
          if (res && res.totalCount) {
            const { data, totalCount } = res
            this.pageInfo.totalNum = totalCount
            this.tableList = data || []
          } else {
            this.tableList = res || []
          }
        })
    },
    /**
     * dialog对话框数据处理
     * @opts {*}
     */
    showDialog(opts) {
      this.dialogObj = {
        isShow: true,
        isEdit: opts.isEdit || false,
        title: opts.title || '新增长租计费规则',
        initData: opts.initData
      }
    },
    /**
     * dialog新增、编辑处理函数
     */
    dialogConfirm() {
      const childRef = this.$refs.childRef
      childRef.$refs.formRef.validate(valid => {
        if (valid) {
          const { startTime, endTime, beforeMoney, money = '', isUse, ...other } = childRef.formModel
          const deleteIds = childRef.deleteIds // 删除含id值
          if (endTime && new Date(startTime).getTime() > new Date(endTime).getTime()) {
            return this.$msgTip('套餐开始时间不能大于结束时间', 'warning')
          }
          this.$api.settings
            .fetch('addRentthePackage', {
              isUse: this.dialogObj.isEdit ? 0 : isUse,
              beforeMoney: beforeMoney * 100,
              money: money === '' ? beforeMoney * 100 : money * 100,
              endTime,
              startTime,
              deleteIds,
              ...other
            })
            .then(() => {
              this.responeHandle(this.dialogObj.isEdit ? '更新成功' : '新增成功')
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 启用禁用
    disabledStatus(params) {
      this.$api.settings.fetch('updateIsUse', params).then(() => {
        this.responeHandle(params.isUse === 1 ? '启用成功' : '禁用成功')
      })
    }
  }
}
</script>
